const os = require('os');
const fs = require('fs');
const path = require('path');
const https = require('https');
const jsdom = require('jsdom');
const streams = require('memory-streams');

const { JSDOM } = jsdom;
const cd = new Date();
const todayPictureName = `${cd.getFullYear()}-${cd.getMonth() + 1}-${cd.getDate()}.jpg`;
const targetDictionary = path.join(os.homedir(), 'Pictures', 'bing-wallpapers');

if (!(fs.existsSync(targetDictionary) && fs.statSync(targetDictionary).isDirectory())) {
  fs.mkdirSync(targetDictionary, { recursive: true });
}

https
  .get('https://cn.bing.com/?mkt=zh-CN', (res) => {
    let writer = new streams.WritableStream();
    res.on('data', (d) => {
      writer.write(d);
    });

    res.on('end', () => {
      const dom = new JSDOM(writer.toString());
      const wrapperedPathname = dom.window.document.querySelector('.img_cont').style.backgroundImage;
      const pathname = wrapperedPathname.slice(5, wrapperedPathname.length - 2);
      writer = fs.createWriteStream(path.join(targetDictionary, todayPictureName));
      https
        .get(`https://cn.bing.com/${pathname}`, (innerRes) => {
          innerRes.on('data', (d) => writer.write(d));
          innerRes.on('end', () => {
            console.log(`${todayPictureName} completed.`);
          });
        })
        .on('error', (e) => {
          console.error(e);
        });
    });
  })
  .on('error', (e) => {
    console.error(e);
  });
